package com.jms.fu.action;


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;



import com.jms.fu.exception.DAOException;
import com.jms.fu.form.UploadForm;
import com.jms.fu.model.bean.App;
import com.jms.fu.model.bo.AppBO;

public class UploadAppAction extends Action {
	private static Logger logger = Logger.getLogger(LoginAction.class);

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		UploadForm uploadForm = (UploadForm) form;
		AppBO appbo = new AppBO();
		if (uploadForm.getAppName() == null
				|| "".equals(uploadForm.getAppName())) {
			try {
				PrintWriter out = response.getWriter();
				out.print("AppNameNull");
				out.close();
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (uploadForm.getCategory() == null
				|| "".equals(uploadForm.getCategory())) {
			try {
				PrintWriter out = response.getWriter();
				out.print("CategoryNull");
				out.close();
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (uploadForm.getRequireOS() == null
				|| "".equals(uploadForm.getRequireOS())) {
			try {
				PrintWriter out = response.getWriter();
				out.print("RequireOSNull");
				out.close();
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (uploadForm.getPrice() < 0) {
			try {
				PrintWriter out = response.getWriter();
				out.print("PriceFail");
				out.close();
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		if (uploadForm.getAppData().getFileSize() == 0) {
			try {
				PrintWriter out = response.getWriter();
				out.print("AppDataNull");
				out.close();
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		FileOutputStream outputStream = null;

		try {
			// write application to disk
			String path = "Data/App/" + uploadForm.getCategory() + "/"
					+ uploadForm.getAppName();
			int i = 1;
			if (!appbo.checkPath(path)) {
				do {
					path = "Data/App/" + uploadForm.getCategory() + "/"
							+ uploadForm.getAppName().toLowerCase() + "(" + i
							+ ")";
					i++;
				} while (!appbo.checkPath(path));
			}
			appbo.writeFileToFolder(uploadForm.getAppData(), getServlet()
					.getServletContext().getRealPath("/") + path);
			// upload app avatar
			String avatarPath = path + "/Avatar";
			if (uploadForm.getAppAvatar().getFileSize() != 0) {
				appbo.writeFileToFolder(uploadForm.getAppAvatar(), getServlet()
						.getServletContext().getRealPath("/") + avatarPath);
			}
			// write image description
			ArrayList<FormFile> imageFiles = uploadForm.getAppImage();
			String imagePath = path + "/Images";
			if (imageFiles.size() != 0) {
				for (FormFile imageFile : imageFiles) {
					if(imageFile.getFileSize()!=0){
					appbo.writeFileToFolder(imageFile, getServlet()
							.getServletContext().getRealPath("/") + imagePath);
					}
				}
			}
			// write to database
			HttpSession session = request.getSession();
			App app = new App();
			app.setAppName(uploadForm.getAppName());
			app.setCategory(uploadForm.getCategory());
			app.setDateUpload(new Date());
			app.setDescription(uploadForm.getDescription());
			app.setDevId((String) session.getAttribute("username"));
			app.setLink(path);
			app.setPrice(uploadForm.getPrice());
			app.setRequireOS(uploadForm.getRequireOS());
			DecimalFormat f = new DecimalFormat("##.00");
			app.setSize(f
					.format(((float) uploadForm.getAppData().getFileSize()) / 1048576)
					+ " MB");
			app.setUpVersion(uploadForm.getVersion());
			app.setNumberOfDownload(0);
			app.setRate(0);
			appbo.uploadApp(app);

			PrintWriter out = response.getWriter();
			out.print("Success");
			out.close();
			return null;

		} catch (DAOException | IOException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
			return null;
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
